const moment = require('moment')

const md5 = require('md5')

const fs = require('fs').promises;

const Path = require('path')

// 格式化时间
exports.formatTime = time => moment(time).format('YYYY-MM-DD HH:mm:ss')

// 处理成功响应
exports.success = ({ ctx, res = null, message = '请求成功' })=> {
  ctx.body = {
    code: 0,
    data: res,
    message
  }
  ctx.status = 200
}

exports.md5 = (str) => {
  return md5(str)
}


exports.startOfDay = (time, format='YYYY-MM-DD HH:mm:ss') => moment(time).startOf('day').hours(0).format(format)

exports.endOfDay = (time, format='YYYY-MM-DD HH:mm:ss') => moment(time).endOf('day').hours(0).format(format)


exports.formatHistoryWarn = (data)=> {
  const curdate = moment().format('YYYY-MM-DD')
  const curHour = moment().format('HH')
  const result = []
  for(let i=0; i<=curHour; i++) {
    let h = i < 10 ? '0' + i : i
    let dateHour = curdate + ' ' + h
    let val = data[dateHour]||0
    result.push({
      hours: dateHour, 
      num: val
    })
  }
  return result

}

//删除文件
exports.delFile = async(path, dir) => {
  if(!path) return
  const fpath = Path.join(
    dir,
    "app",
    path
  );
  console.log(fpath, 'delfile....')
  await fs.unlink(fpath)
}